﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;
using TomanuExtensions;
using TomanuExtensions.Utils;

namespace AmiEmuLib.Configuration.FloppySoundConfig
{
    /// <summary>
    /// Sigle sound file with path and name.
    /// </summary>
    public class FloppySound : XmlBase
    {
        /// <summary>
        /// Path to sound in resources.
        /// </summary>
        public string Path { get; internal set; }

        /// <summary>
        /// Sound name.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="a_name"></param>
        public FloppySound(string a_name)
        {
            Name = a_name;
            Path = "";
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="a_reader"></param>
        public FloppySound(XmlReader a_reader)
            : base(a_reader)
        {
        }

        /// <summary>
        /// Get sounds bytes.
        /// </summary>
        /// <returns></returns>
        public byte[] GetBytes()
        {
            using (var stream = GetStream())
            {
                if (stream == null)
                    return null;

                byte[] sound = new byte[stream.Length];
                stream.Read(sound, 0, (int)stream.Length);
                return sound;
            }
        }

        /// <summary>
        /// Get sound stream.
        /// </summary>
        /// <returns></returns>
        public Stream GetStream()
        {
            if (Path == "")
                return null;

            return StreamExtensions.FromResource(typeof(FloppySound), Path);
        }

        /// <summary>
        /// Is sound file exists.
        /// </summary>
        public bool Exists
        {
            get
            {
                return Path != "";
            }
        }

        public override string ToString()
        {
            return String.Format("{0} {1}", Name, Exists ? "" : "(not present)");
        }

        protected override void ReadXml(XmlReader a_reader)
        {
            Name = a_reader.GetAttribute("Name");
            Path = a_reader.ReadElementContentAsString(GetType().Name);
        }

        public override void WriteXml(XmlWriter a_writer)
        {
            a_writer.WriteStartElement(GetType().Name);

            a_writer.WriteAttribute("Name", Name);
            a_writer.WriteString(Path);

            a_writer.WriteEndElement();
        }
    }
}
